//
//  HLrcView.m
//  HMusicPlayer
//
//  Created by Hament on 14/9/22.
//  Copyright (c) 2014年 HJ. All rights reserved.
//

#import "HLrcView.h"
#import "HCoreConfig.h"
#import "HskinManager.h"
#import "HLyricItem.h"
#import "HlyricsParser.h"
#import "HMainWC.h"
#import "HSQLManager.h"
#import "HJAudioPlayer.h"
#import "HSongItem.h"
#import "iTunes.h"
@interface HLrcView ()<NSMenuDelegate>
@property (nonatomic,strong) NSArray * supportDragTypesArr;//支持
@property (nonatomic,strong) NSMenu *  pTableMenu;
@property (nonatomic) BOOL isHasTimeline;//歌词是否有时间轴
@end


@implementation HLrcView 



-(void)awakeFromNib {
    

    /*注册允许拖放的类型*/
    self.supportDragTypesArr=@[(id)kUTTypeFileURL];
    [self.tableV registerForDraggedTypes:self.supportDragTypesArr];
    [self.tableV setDraggingSourceOperationMask:NSDragOperationGeneric forLocal:NO];//是否只局限于本地拖放
    [self.tableV setSelectionHighlightStyle:NSTableViewSelectionHighlightStyleNone];
    [self.tableV setMenu:self.pTableMenu];
    
    [self.tableV setDoubleAction:@selector(doubleClick)];
    self.remindLab.stringValue=NSLocalizedString(@"Drag lyrics reminder", nil);
    
    
}



#pragma mark  ---------- lazylaoding--------

-(NSMutableArray *)dataSource {
    
    
    if (!_dataSource) {
        _dataSource=[[NSMutableArray alloc] init];
    }
    return _dataSource;
}


-(NSMenu*)pTableMenu{
    
    if (!_pTableMenu) {
        _pTableMenu=[[NSMenu alloc] init];
        [_pTableMenu setAutoenablesItems:YES];
        _pTableMenu.delegate=self;
        NSMenuItem * t1=[[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Clean", nil) action:@selector(cleanAndRemoveLyrics) keyEquivalent:@""];
        t1.tag=1000;
        [_pTableMenu addItem:t1];
        
    }
    
    
    return _pTableMenu;
}

#pragma mark  ---------- 业务逻辑--------

-(void)doubleClick{

    //全屏模式
    if (self.window.styleMask & NSFullScreenWindowMask) {
        return;
    }
    
    [[HMainWC shareWc] toggleLyricDrawer:nil];
}


//根据歌词文件加载歌词
-(void)loadDataWithLyricPath:(NSString*)localLypath withAlert:(BOOL)flag{
    

    if(localLypath) {
    //如果歌词文件存在
        if ([[NSFileManager defaultManager] fileExistsAtPath:localLypath]) {

            [HlyricsParser parserLRCFileWithLocalPath:localLypath reqMainQueue:YES subTheadfinisHandel:^(BOOL success,BOOL hasTimeLine, NSArray * arr){

                self.isHasTimeline=hasTimeLine;
                
                //如果解析成功
                if (success) {
                    
                [_dataSource removeAllObjects];
                    
                [_dataSource addObjectsFromArray:arr];
                 
                //last 插一个空白行
                HLyricItem * litem=[[HLyricItem alloc] init];
                litem.beginDuration=InvalidSoundDuration;
                litem.contentStr=@"";
    
                [_dataSource addObject:litem];
        
                [self.remindLab setHidden:YES];
                [self reloadlyricStyleAndData];

                [_tableV reloadData];
                    
                    
//                    for(HLyricItem * item in _dataSource){
//                    
//                        debugLog(@"time:%d ,str:%@",item.beginDuration,item.contentStr);
//                    
//                    }
                    
                } else {
                
                
                     [self.remindLab setHidden:NO];
                    if(flag) {
                    
                        [HCoreConfig alertWithTitle:NSLocalizedString(@"The file is unreadable", nil) window:self.window];
                    
                    }
                
                
                }
                
                
            }];
        } else {
        
         [self.remindLab setHidden:NO];
        
        }
    } else {
    
     [self.remindLab setHidden:NO];
    }


}




//清空歌词UI并删除数据库
-(void)cleanAndRemoveLyrics{

    [self.remindLab setHidden:NO];
    
    
    HSongItem * si=[HJAudioPlayer sharePlayer].currentPlaySongItem;
    //删除数据库songinfo歌曲信息，并删除歌词文件
      [HSQLManager removeThelyricInfoWithSongItem:si];
    
    
    
    //如果是itunes的歌曲，还要清除掉itunes的歌词信息
    if(si &&[HCoreConfig checkSongisBelongToItunesWithPath:si.localPath]){
    
        //检查itunes是否有内嵌歌词
        iTunesFileTrack * ift=[HCoreConfig getItunesFiletrackWithPath:si.localPath];
        
        if (ift) {
            ift.lyrics=@"";
        }
        
    }
    
    

    [self cleanLyrics];
}


//清空歌词UI
-(void)cleanLyrics{

    
 [self.dataSource removeAllObjects];
 [_tableV reloadData];
    
[_tableV scrollPoint:NSMakePoint(0, NSHeight(_tableV.frame))];
 //加上显示歌词的标语
    

}

//根据用户设置字体或全屏变化时重设
-(void)reloadlyricStyleAndData{

    //全屏
    if ([HMainWC shareWc].window.styleMask & NSFullScreenWindowMask) {
        self.lyricfont=[NSFont systemFontOfSize:[[HCoreConfig shareConfig] lyricsFullScreenFontSize]];
    } else {
        self.lyricfont=[NSFont systemFontOfSize:[[HCoreConfig shareConfig] lyricsFontSize]];
    
    }
    
    self.textWidth=NSWidth(self.frame)-12;//预算slider
    
    [self.tableV reloadData];


}


//根据时间定为高亮row
-(void)locateHighlightRowWithduration:(NSUInteger)duration{

    
   
     int count=(int)self.dataSource.count;
    if (count==0 || self.isHasTimeline==NO) {
        return;
    }

    
    
    
     dispatch_async(dispatch_get_main_queue(),^{
    int therow=0;
    
    
    for (int i=(count-1); i>0; i--) {
        
        HLyricItem * litem=[self.dataSource objectAtIndex:i];
        if(duration>litem.beginDuration) {
            therow=i;
           // debugLog(@"row:%d,beginduration:%d,current:%d,str:%@",therow,litem.beginDuration,duration,litem.contentStr);
            break;
        }
        
    }

         
//          NSRect rowRect = [self.tableV rectOfRow:therow];
//         debugLog(@"rowRect:%@",NSStringFromRect(rowRect));
         
         NSRect rowRect = [self.tableV rectOfRow:therow];
         NSRect viewRect = [[self.tableV superview] frame];
         NSPoint scrollOrigin = rowRect.origin;
         scrollOrigin.y = scrollOrigin.y + (rowRect.size.height - viewRect.size.height) / 2;
         if (scrollOrigin.y < 0) scrollOrigin.y = 0;
         [[[self.tableV superview] animator] setBoundsOrigin:scrollOrigin];
         
         
    [self.tableV enumerateAvailableRowViewsUsingBlock:^(NSTableRowView *rowView, NSInteger row) {
        
        //第几行第几列
        for (NSInteger column = 0; column < rowView.numberOfColumns; column++) {
            NSView *cellView = [rowView viewAtColumn:column];
            // Is this an NSTableCellView?
            //debugLog(@"row is:%d",row);
            
            NSTableCellView *tableCellView = (NSTableCellView *)cellView;

            if (row==therow) {
                tableCellView.textField.textColor=[HCoreConfig shareConfig].currentSkinManager.lyrcisHightlightColor ;
            } else {
                
                tableCellView.textField.textColor=[HCoreConfig shareConfig].currentSkinManager.lyrcisNormalColor;
            }

            
            
        }
        
    }];
    
    [self.tableV scrollRowToVisible:therow];
        
     });
}



#pragma mark  ---------- tableview delegate (view based)--------

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView{
    
    
    return [self.dataSource count];
}


- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row{
    
    return [self.dataSource objectAtIndex:row];
    
}

// This method is optional if you use bindings to provide the data
- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
    
    //debugLog(@"loop row:%ld",row);

    HLyricItem* entity = [self.dataSource objectAtIndex:row];
    

    NSTableCellView * cellView=[tableView makeViewWithIdentifier:@"lyricCell" owner:tableView];
    
    NSString * lyric=CHECKSTR(entity.contentStr);
    cellView.textField.font=self.lyricfont;
    cellView.textField.stringValue=lyric;
    

     //不能设置frame,否则autoresize失效
    //cellView.textField.frame=NSMakeRect(0, 0, self.textWidth, minHeight);

//    if (row==1) {
//         cellView.textField.textColor=[HCoreConfig shareConfig].currentSkinManager.lyrcisHightlightColor ;
//    } else {
//    
//        cellView.textField.textColor=[HCoreConfig shareConfig].currentSkinManager.lyrcisNormalColor;
//    }
    
    
     cellView.textField.textColor=[HCoreConfig shareConfig].currentSkinManager.lyrcisNormalColor;

    
    return cellView;
    
}



- (BOOL)tableView:(NSTableView *)tableView shouldSelectRow:(NSInteger)row{

    return NO;
}

static  NSTableCellView * thecellView;
- (CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row{

    if (self.dataSource.count>0) {
       HLyricItem* entity = [self.dataSource objectAtIndex:row];
        
        if(!thecellView){
       thecellView=[tableView makeViewWithIdentifier:@"lyricCell" owner:tableView];
        }
        
        NSString * lyric=CHECKSTR(entity.contentStr);
        thecellView.textField.font=self.lyricfont;
        thecellView.textField.stringValue=lyric;

        
        CGFloat minHeight = [((NSTextFieldCell *)[thecellView.textField cell]) cellSizeForBounds:NSMakeRect(0, 0, self.textWidth, FLT_MAX)].height;
        
        return minHeight+4;
    }


    return 20;
}

/*
- (void)tableViewSelectionDidChange:(NSNotification *)notification {
    
    
    
  
    
}
*/


#pragma mark -----拖放有关的代理-----
// 2.确定拖拽的动作信息,该方法会随着拖放位置改变而执行
- (NSDragOperation)tableView:(NSTableView *)tableView validateDrop:(id<NSDraggingInfo>)info proposedRow:(NSInteger)row proposedDropOperation:(NSTableViewDropOperation)dropOperation {
    // NSLog(@"row:%d,song opera:%lu",row,dropOperation);
    

    
    NSDragOperation result=NSDragOperationCopy;
    
     [self.tableV setDropRow:0 dropOperation:NSDragOperationCopy];
    
 
   
    return result;
}

//鼠标松手,落下操作
- (BOOL)tableView:(NSTableView *)tableView acceptDrop:(id<NSDraggingInfo>)info row:(NSInteger)row dropOperation:(NSTableViewDropOperation)dropOperation {

    NSPasteboard* zPBoard = [info draggingPasteboard];

    NSString * zStrAvailableType = [zPBoard availableTypeFromArray:self.supportDragTypesArr];//该方法按顺序
    if ( UTTypeConformsTo((__bridge CFStringRef)zStrAvailableType, kUTTypeURL)) {
        NSArray * arr=[info draggingPasteboard].pasteboardItems;
        //NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
        NSFileManager * fileManager=[NSFileManager defaultManager];


            NSPasteboardItem * pasteItem=arr[0];
            id item=[pasteItem stringForType:zStrAvailableType];
            
            NSURL *url = [[NSURL alloc] initWithPasteboardPropertyList:item ofType:zStrAvailableType];
            NSString * ext=url.pathExtension.lowercaseString;
//            if ([ext isEqualToString:@"lrc"] || [ext isEqualToString:@"krc"]) {
//                
//                debugLog(@"url:%@",url.path);
//                
//            } else {
//            //提示
//                debugLog(@"不符合的格式");
//            
//            }
        
        NSString * sourcePath=url.path;
        //文件可读
        if ([fileManager isReadableFileAtPath:sourcePath]) {
            
            
            [HlyricsParser parserLRCFileWithLocalPath:sourcePath reqMainQueue:YES subTheadfinisHandel:^(BOOL success,BOOL hasTimeline, NSArray * arr){
                
                self.isHasTimeline=hasTimeline;
                
                //如果解析成功
                if (success) {
                    
                    [_dataSource removeAllObjects];
                    
                    [_dataSource addObjectsFromArray:arr];
                    
                    //last 插一个空白行
                    HLyricItem * litem=[[HLyricItem alloc] init];
                    litem.beginDuration=InvalidSoundDuration;
                    litem.contentStr=@"";
                    
                    [_dataSource addObject:litem];
                    
                    [self.remindLab setHidden:YES];
                    [self reloadlyricStyleAndData];
                    
                    [_tableV reloadData];
                    
                    
                    //文件解析成功后才插入数据库
                    HSongItem * songitem=[HJAudioPlayer sharePlayer].currentPlaySongItem;
                    if(songitem) {
                    
                        NSString * filename=[HCoreConfig generateMD5Hash];
                        NSString * desPath=[lyricsCache stringByAppendingPathComponent:filename];
                        desPath=[desPath stringByAppendingPathExtension:ext];
                        
                        [fileManager removeItemAtPath:desPath error:nil];
                        [fileManager copyItemAtPath:sourcePath toPath:desPath error:nil];
                        
                        
                        [HSQLManager insertSonginfoWithSongItem:songitem andInfo:@{@"lyricsLocalPath":desPath}];
                    }
                    
                    
                    
                    //                    for(HLyricItem * item in _dataSource){
                    //
                    //                        debugLog(@"time:%d ,str:%@",item.beginDuration,item.contentStr);
                    //
                    //                    }
                    
                } else {

                        [HCoreConfig alertWithTitle:NSLocalizedString(@"The file is unreadable", nil) window:self.window];
          
                }
                
                
            }];
            
            
            
            
        } else {
        
          [HCoreConfig alertWithTitle:NSLocalizedString(@"The file is unreadable", nil) window:self.window];

        }
        
        

    
    
    }

    return YES;

}
#pragma mark  ----------nsmenu delegate--------

//
//- (void)menuWillOpen:(NSMenu *)menu {
//    
//    //空白行不理会 //group 不理会
//    NSUInteger clickrow= [self.tableV clickedRow];
//    if (clickrow==-1 ) {
//        [menu cancelTracking];
//    }
//    
//    
//    
//    
//    
//    
//}








@end
